/*
 * SpriteComponent.cpp
 *
 *  Created on: May 13, 2012
 *      Author: mklingen
 */

#include "SpriteComponent.h"
#include "GameWindow.h"
#include "../MathUtils.h"

namespace kling
{

    SpriteComponent::SpriteComponent(std::string fileName, GameComponentManager* componentManager, std::string name, GlobalComponentID id)
        : GameComponent(componentManager, name, id)
    {
        m_imageResource = componentManager->GetGameWindow()->GetResourceManager()->GetResource<ImageResource>(fileName);
    }

    SpriteComponent::~SpriteComponent()
    {
        if(m_sprite != NULL)
        {
            delete m_sprite;
            m_sprite = NULL;
        }
    }

    void SpriteComponent::Update(double dt)
    {
        if(IsInitialized())
        {
            m_sprite->SetPosition(m_globalPose.translation().x(), -m_globalPose.translation().y());
            m_sprite->SetRotation(MathUtils::RadiansToDegrees(m_globalRotation));
        }

        GameComponent::Update(dt);
    }

    void SpriteComponent::Render(double dt)
    {
        if(IsInitialized())
        {
            m_componentManager->GetGameWindow()->Draw(*m_sprite);
        }

        GameComponent::Render(dt);
    }

    void  SpriteComponent::Initialize()
    {
        if(m_imageResource != NULL)
        {
            m_sprite = new sf::Sprite(*(m_imageResource->GetImage()));
            m_sprite->SetCenter(m_imageResource->GetImage()->GetWidth() / 2, m_imageResource->GetImage()->GetHeight() / 2);
        }

        GameComponent::Initialize();
    }

} /* namespace kling */
